package servlet.admin;

import dao.AdminDao;
import entity.Admin;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/adminLogin")
public class AdminLoginServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String username = request.getParameter("username");
        System.out.println(username);
        String password = request.getParameter("password");

        AdminDao adminDao = new AdminDao();
        try {
            Admin admin = adminDao.login(username, password);
            if (admin != null) {
                System.out.println("11");
                HttpSession session = request.getSession();
                session.setAttribute("admin", admin);
                response.sendRedirect("admin/dashboard.jsp");
            } else {
                request.setAttribute("error", "用户名或密码错误");
                request.getRequestDispatcher("adminLogin.jsp").forward(request, response);
            }
        } catch (Exception e) {
            request.setAttribute("error", "登录失败：" + e.getMessage());
            request.getRequestDispatcher("adminLogin.jsp").forward(request, response);
        }
    }
}